<template>
  <div>
    <!-- 聊天信息展示区 -->
    <div class="msg" ref="dialogueContent">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message"
        :class="{
          sent: message.senderId === UserInfo.id,
          received: message.senderId !== UserInfo.id,
        }"
      >
        <div class="message-header" v-if="message.senderId !== UserInfo.id">
          <img :src="message.avatarUrl" alt="avatar" class="avatar" />
          <span>{{ message.userName }}</span>
        </div>

        <div class="message-header" v-if="message.senderId === UserInfo.id">
          <span>{{ message.userName }}</span>
          <img :src="message.avatarUrl" alt="avatar" class="avatar" />
        </div>

        <div class="message-content">
          <!-- <div>{{ message.content }}</div> -->
          <div v-html="message.content" v-viewer></div>
        </div>
      </div>
    </div>

    <!-- 表情选择区 -->
    <div class="Picker" v-if="showemoji">
      <Picker @select="showEmoji" :i18n="I18N" />
    </div>

    <!-- 输入区 -->
    <div class="input-top">
      <i
        class="el-icon-back"
        @click="$emit('callBack')"
        style="font-size: 23px; cursor: pointer"
        title="返回"
      ></i>
      <i
        class="iconfont icon-biaoqing"
        style="padding: 10px; font-size: 25px; cursor: pointer"
        :class="{ color: showemoji == true }"
        @click="showemoji = !showemoji"
      ></i>

      <el-upload
      ref="upload"
        style="display: inline-block"
        :action="uploadUrl"
        name="multipartFile"
        :headers="headers"
        :on-success="handleAvatarSuccess"
        :limit="1"
      >
        <i
          class="el-icon-picture"
          style="font-size: 23px; cursor: pointer"
          title="上传图片"
        ></i>
      </el-upload>
    </div>

    <!-- 输入框 -->
    <div class="input-area">
      <textarea
        v-model="content"
        id="textarea_art"
        placeholder="请输入您的问题..."
        @keydown.enter="sendMessage"
      ></textarea>
      
      <!-- <div class="el-icon-position" @click="sendMessage"></div> -->
    </div>
  </div>
</template>

<script>
import { Picker } from "emoji-mart-vue";

const I18N = {
  search: "搜索",
  notfound: "No Emoji Found",
  categories: {
    search: "搜索结果",
    recent: "经常使用",
    smileys: "表情与情感",
    people: "人物与身体",
    activity: "活动",
    places: "旅行与地理",
    objects: "物品",
    symbols: "符号标志",
    flags: "旗帜",
    custom: "自定义",
  },
};

export default {
  props: {
    room: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      I18N: I18N,
      showemoji: false,
      content: "",
      messages: [], // 保存所有聊天消息
      socket: null, // WebSocket连接
      type: "user", // 当前用户类型
      UserInfo: {},
      uploadUrl: process.env.VUE_APP_BASE_API + "/upload",
    };
  },
  components: {
    Picker,
  },
  computed: {
      headers() {
        return {
          Authorization: this.$store.state.token
        }
      }
    },
  mounted() {
    if (this.$store.state.UserInfo?.id != undefined) {
      this.UserInfo = this.$store.state.UserInfo;
    } else {
      this.$message.warning("请先登录");
      this.$router.go(-1);
    }
    this.initWebSocket(); // 初始化 WebSocket
    // 初始化消息
    this.getChatRoomMsg();
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if(res.code==200){
        const message = {
        avatarUrl: this.UserInfo.avatar, // 用户头像URL，您可以替换成真实的头像路径
        userName: this.UserInfo.nickname, // 用户昵称
        content: `<img src="${res.data}" alt="图片" style="width: 100px;height: 100px;">`, // 消息内容
        senderId: this.UserInfo.id, // 发送人ID
        receiveUserId: this.roomId, // 接收人ID
        roomId: this.roomId, // 房间ID
      };
        this.socket.send(JSON.stringify(message)); // 发送消息到后端
      // 发送成功后将消息显示在聊天框中
      this.messages.push(message);
      }
       this.$refs.upload.clearFiles()
      },
    // 实时滚动到底部
    observeContentChanges() {
      const dialogueContent = this.$refs.dialogueContent;
      if (dialogueContent) {
        new MutationObserver(() => {
          // 滚动到底部
          dialogueContent.scrollTop = dialogueContent.scrollHeight;
        }).observe(dialogueContent, {
          childList: true,
          subtree: true,
        });
      }
    },
    getChatRoomMsg() {
      this.$api.customerService.getChatRoomMsgList(this.room).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.messages = res.data;
          this.observeContentChanges();
        }
      });
    },
    // 初始化 WebSocket 连接
    initWebSocket() {
      const socketUrl = `${process.env.VUE_APP_SOCKET_PATH}/chat_room/${this.UserInfo.id}/${this.room}/${this.type}`;
      this.socket = new WebSocket(socketUrl);

      // WebSocket 连接成功时
      this.socket.onopen = () => {
        console.log("WebSocket连接成功");
      };

      // WebSocket 接收到消息时
      this.socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        console.log(data);
        this.messages.push(data); // 将接收到的消息添加到消息列表
      };

      // WebSocket 连接关闭时
      this.socket.onclose = () => {
        console.log("WebSocket连接已关闭");
      };

      // WebSocket 发生错误时
      this.socket.onerror = (error) => {
        console.error("WebSocket发生错误", error);
      };
    },

    // 选择表情
    showEmoji(emoji) {
      const str = emoji.native;
      var oText = document.getElementById("textarea_art");
      var index = this.getCursortPosition(oText);
      this.$nextTick(() => {
        this.insert(oText, str, index);
      });
    },

    // 插入表情
    insert(oText, varstr, index) {
      var text = this.content;
      let startStr = text.substring(0, index);
      let endStr = text.substring(index, text.length);
      this.content = startStr + varstr + endStr;
      setTimeout(() => {
        this.setCaretPosition(oText, index + 2);
      }, 10);
    },

    // 获取光标位置
    getCursortPosition(obj) {
      var cursorIndex = 0;
      if (document.selection) {
        obj.focus();
        var range = document.selection.createRange();
        range.moveStart("character", -obj.value.length);
        cursorIndex = range.text.length;
      } else if (obj.selectionStart || obj.selectionStart == 0) {
        cursorIndex = obj.selectionStart;
      }
      return cursorIndex;
    },

    // 设置光标位置
    setCaretPosition(ctrl, pos) {
      if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos);
      } else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd("character", pos);
        range.moveStart("character", pos);
        range.select();
      }
    },

    // 发送消息
    sendMessage() {
      if (!this.content.trim()) return; // 消息为空时不发送
      const message = {
        avatarUrl: this.UserInfo.avatar, // 用户头像URL，您可以替换成真实的头像路径
        userName: this.UserInfo.nickname, // 用户昵称
        content: this.content, // 消息内容
        senderId: this.UserInfo.id, // 发送人ID
        receiveUserId: this.roomId, // 接收人ID
        roomId: this.roomId, // 房间ID
      };
      console.log(message);
      this.socket.send(JSON.stringify(message)); // 发送消息到后端
      // 发送成功后将消息显示在聊天框中
      this.messages.push(message);
      this.content = ""; // 清空输入框
      this.observeContentChanges();
    },
  },
};
</script>



<style lang="less" scoped>
::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 0px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 0px;
}
.color {
  color: #b2d77e !important;
}
.msg {
  height: 75vh;
  overflow: auto;
}
.Picker {
  position: fixed;
  bottom: 80px;
}
/deep/ .el-upload-list{
display: none !important;
}
.input-top {
  position: fixed;
  bottom: 62px;
  background: white;
  width: 450px;
}

.input-area {
  position: fixed;
  display: flex;
  align-items: center;
  width: 450px;
  bottom: 15px;

  textarea {
    flex: 1;
    border: none;
    padding: 8px;
    &:focus {
      outline: none;
      border: none;
    }
  }

  .el-icon-position {
    position: absolute;
    right: -22px;
    font-size: 20px;
    cursor: pointer;
  }
}

.message {
  padding: 10px;
  border-bottom: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.message.sent {
  align-items: flex-end;
  text-align: right;
}

.message.received {
  align-items: flex-start;
  text-align: left;
}

.message-header {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 0 10px;
}

.message-content {
  margin-top: 5px;
  background-color: #f1f1f1;
  padding: 8px;
  border-radius: 5px;
}
</style>
